<script setup>
import {onMounted, ref, computed} from 'vue';
import * as XLSX from 'xlsx';
import {ElMessage, ElMessageBox} from "element-plus";
// 搜索信息
const searchInfo = ref({selectedUniversityLevels: [], isJoinPlanTime: '', name: '', account: '', selectedUniversity: ''})
// 表格数据
const tableData = ref([
  {    id: 1,
    name: '李明',
    account: 'LM20250902',
    struct: '河南工业和信息化职业学院,计算机应用技术,2025级,1班',
    complishedStatus: 80,
    isJoinPlanTime: 1,
    family: [
      {
        id: 1,
        name: '症状自评量表（SCL-90）',
        complishedStatus: 80,
      }
    ],
  },
  {
    id: 2,
    name: '李四',
    account: 'lisi002',
    struct: '河南工业和信息化职业学院,计算机应用技术,2025级,2班',
    complishedStatus: 100,
    isJoinPlanTime: 1,
    family: [
      {
        id: 3,
        name: 'MBTI性格类型测试问卷',
        complishedStatus: 100,
      }
    ],
  },
  {
    id: 3,
    name: '王五',
    account: 'wangwu003',
    struct: '河南工业和信息化职业学院,计算机应用技术,2025级,3班',
    complishedStatus: 50,
    isJoinPlanTime: 0,
    family: [
      {
        id: 4,
        name: '学习倦怠量表',
        complishedStatus: 50,
      }
    ],
  },
  {
    id: 4,
    name: '赵六',
    account: 'zhaoliu004',
    struct: '河南工业和信息化职业学院,计算机应用技术,2024级,1班',
    complishedStatus: 60,
    isJoinPlanTime: 1,
    family: [
      {
        id: 5,
        name: '青少年生活事件量表',
        complishedStatus: 60,
      },
      {
        id: 6,
        name: '师生关系量表',
        complishedStatus: 60,
      }
    ],
  },
  {
    id: 5,
    name: '孙七',
    account: 'sunqi005',
    struct: '河南工业和信息化职业学院,计算机应用技术,2024级,2班',
    complishedStatus: 0,
    isJoinPlanTime: 0,
    family: []
  },
  {
    id: 6,
    name: '周八',
    account: 'zhouba006',
    struct: '河南工业和信息化职业学院,计算机应用技术,2024级,3班',
    complishedStatus: 75,
    isJoinPlanTime: 1,
    family: [
      {
        id: 7,
        name: '霍兰德职业倾向测验量表',
        complishedStatus: 75,
      }
    ],
  },
  {
    id: 7,
    name: '吴九',
    account: 'wujiu007',
    struct: '河南工业和信息化职业学院,计算机应用技术,2023级,1班',
    complishedStatus: 40,
    isJoinPlanTime: 1,
    family: [
      {
        id: 8,
        name: 'SCL-90症状自评量表',
        complishedStatus: 40,
      }
    ],
  },
  {
    id: 8,
    name: '郑十',
    account: 'zhengshi008',
    struct: '河南工业和信息化职业学院,计算机应用技术,2023级,2班',
    complishedStatus: 100,
    isJoinPlanTime: 1,
    family: [
      {
        id: 9,
        name: '心理韧性量表',
        complishedStatus: 100,
      },
      {
        id: 10,
        name: '自我认同感量表',
        complishedStatus: 100,
      }
    ],
  },
  {
    id: 9,
    name: '钱一',
    account: 'qianyi009',
    struct: '河南工业和信息化职业学院,计算机应用技术,2023级,3班',
    complishedStatus: 25,
    isJoinPlanTime: 0,
    family: [
      {
        id: 11,
        name: '时间管理自我监控量表',
        complishedStatus: 25,
      }
    ],
  },
  {
    id: 10,
    name: '孙二',
    account: 'suner010',
    struct: '河南工业和信息化职业学院,计算机应用技术,2022级,1班',
    complishedStatus: 90,
    isJoinPlanTime: 1,
    family: [
      {
        id: 12,
        name: '情绪自评量表（DASS-21）',
        complishedStatus: 90,
      },
      {
        id: 13,
        name: '家庭亲合量表',
        complishedStatus: 90,
      }
    ],
  },
  {
    id: 11,
    name: '李三',
    account: 'lisang011',
    struct: '河南工业和信息化职业学院,计算机应用技术,2022级,2班',
    complishedStatus: 100,
    isJoinPlanTime: 1,
    family: [
      {
        id: 14,
        name: '青春期性心理健康量表',
        complishedStatus: 100,
      },
      {
        id: 15,
        name: '社会支持评定量表',
        complishedStatus: 100,
      }
    ],
  },
  {
    id: 12,
    name: '张四',
    account: 'zhangs4012',
    struct: '河南工业和信息化职业学院,计算机应用技术,2022级,3班',
    complishedStatus: 0,
    isJoinPlanTime: 0,
    family: []
  },
  {
    id: 13,
    name: '赵五',
    account: 'zhaowu013',
    struct: '河南工业和信息化职业学院,计算机应用技术,2025级,1班',
    complishedStatus: 65,
    isJoinPlanTime: 1,
    family: [
      {
        id: 16,
        name: '创造性倾向问卷',
        complishedStatus: 65,
      }
    ],
  },
  {
    id: 14,
    name: '钱六',
    account: 'qianliu014',
    struct: '河南工业和信息化职业学院,计算机应用技术,2025级,2班',
    complishedStatus: 30,
    isJoinPlanTime: 1,
    family: [
      {
        id: 17,
        name: '考试心理和行为问题症状自评量表',
        complishedStatus: 30,
      }
    ],
  },
  {
    id: 15,
    name: '孙七',
    account: 'sunqi015',
    struct: '河南工业和信息化职业学院,计算机应用技术,2025级,3班',
    complishedStatus: 70,
    isJoinPlanTime: 1,
    family: [
      {
        id: 18,
        name: '大五人格量表简化版',
        complishedStatus: 70,
      }
    ],
  }
])
// tableData复制
const tableDataCopy = ref([])
// 选择组织结构数据 - 河南工业和信息化职业学院四级结构
const universityOptions = ref([
  {
    value: '河南工业和信息化职业学院',
    label: '河南工业和信息化职业学院',
    children: [
      {
        value: '计算机应用技术',
        label: '计算机应用技术',
        children: [
          {
            value: '2025级',
            label: '2025级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' },
            ],
          },
          {
            value: '2024级',
            label: '2024级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' },
            ],
          },
          {
            value: '2023级',
            label: '2023级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' },
            ],
          },
          {
            value: '2022级',
            label: '2022级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' },
            ],
          },
        ],
      },
    ],
  },
])
// 搜索
const search = () => {
  const universityLevels = searchInfo.value.selectedUniversityLevels
  searchInfo.value.selectedUniversity = ''
  if (universityLevels && universityLevels.length > 0) {
    for (const level of universityLevels) {
      searchInfo.value.selectedUniversity += (level + ',')
    }
    searchInfo.value.selectedUniversity = searchInfo.value.selectedUniversity.slice(0, -1)
  }
  tableData.value = []
  for (let i = 0; i < tableDataCopy.value.length; i++) {
    if (searchInfo.value.selectedUniversity && searchInfo.value.selectedUniversity !== '' && searchInfo.value.selectedUniversity !== tableDataCopy.value[i].struct) continue
    if ((searchInfo.value.isJoinPlanTime === 0 || searchInfo.value.isJoinPlanTime === 1) && searchInfo.value.isJoinPlanTime !== tableDataCopy.value[i].isJoinPlanTime) continue
    if (searchInfo.value.name && searchInfo.value.name !== '' && searchInfo.value.name !== tableDataCopy.value[i].name) continue
    if (searchInfo.value.account && searchInfo.value.account !== '' && searchInfo.value.account !== tableDataCopy.value[i].account) continue
    tableData.value.push(tableDataCopy.value[i])
  }
}
// 重置
const reset = () => {
  searchInfo.value = {selectedUniversityLevels: [], isJoinPlanTime: '', name: '', account: '', selectedUniversity: ''}
  search()
}
// 导出数据
const exportInfo = () => {
  const exportData = tableData.value.map(item => {
    const [university, major, className] = item.struct.split(',') || [];
    return {
      '姓名': item.name,
      '账号': item.account,
      '学校': university || '',
      '专业': major || '',
      '班级': className || '',
      '完成度': `${item.complishedStatus}%`,
      '加入计划时间': item.isJoinPlanTime ? '已加入' : '未加入'
    };
  });

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '用户数据');

  const fileName = `用户测评数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
  XLSX.writeFile(workbook, fileName);
}
// 点击查看逻辑实现
const expandedRowKeys = ref([]);
const toggleExpand = (row) => {
  const index = expandedRowKeys.value.indexOf(row.id);
  if (index === -1) {
    expandedRowKeys.value.push(row.id);
  } else {
    expandedRowKeys.value.splice(index, 1);
  }
};
// 处理重做功能
const handleRedo = (row, scaleItem) => {
  ElMessageBox.confirm(
    '您确定要重做该量表吗？重做后当前进度将归为0。',
    '确认重做',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 将当前量表进度归为0
    scaleItem.complishedStatus = 0;
    
    // 重新计算row的总完成度
    if (row.family && row.family.length > 0) {
      const totalProgress = row.family.reduce((sum, item) => sum + item.complishedStatus, 0);
      row.complishedStatus = Math.round(totalProgress / row.family.length);
    } else {
      row.complishedStatus = 0;
    }
    
    ElMessage.success('已重置该量表进度');
  }).catch(() => {
    ElMessage.info('已取消重做');
  });
}

// 计算统计数据
const statistics = computed(() => {
  const totalCount = tableData.value.length;
  const completedCount = tableData.value.filter(item => item.complishedStatus === 100).length;
  const uncompletedCount = totalCount - completedCount;
  
  return {
    totalCount,
    completedCount,
    uncompletedCount,
    invalidReport: 0
  };
})

// onMounted
onMounted(() => {
  tableDataCopy.value = tableData.value
})
</script>

<template>
  <p style="padding: 10px 10px; font-size: 16px;font-weight: 600;">温馨提示：创建团测后，如有用户或组织结构调整，请手动<el-button link type="primary" size="small" style="font-size: 16px;font-weight: 700;" @click="ElMessage.success('已同步数据')">同步数据>>></el-button></p>
  <!-- 搜索部分 -->
  <div class="search-box">
      <el-row>
          <el-col :span="3"></el-col>
          <el-col :span="4">
            <el-cascader :options="universityOptions" clearable style="width: 95%" v-model="searchInfo.selectedUniversityLevels"/>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchInfo.isJoinPlanTime" placeholder="是否加入计划时间" style="width: 95%" >
              <el-option label="未加入" :value="0"/>
              <el-option label="已加入" :value="1"/>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-input v-model="searchInfo.name" style="width: 200px" placeholder="请输入姓名" />
          </el-col>
          <el-col :span="4">
            <el-input v-model="searchInfo.account" style="width: 200px" placeholder="请输入账号" />
          </el-col>
          <el-col :span="5">
            <div>
              <el-button type="primary" @click="search"><el-icon><Search /></el-icon>查询</el-button>
              <el-button type="primary" @click="reset"><el-icon><Remove /></el-icon>重置</el-button>
              <el-button type="primary" @click="exportInfo">导出</el-button>
            </div>
          </el-col>
      </el-row>
  </div>
  <div class="over-box">
      <div class="over-item">
        <div>总人数（人）</div>
        <div>{{ statistics.totalCount }}</div>
      </div>
      <div class="over-item">
          <div>已完成（人）</div>
          <div>{{ statistics.completedCount }}</div>
      </div>
      <div class="over-item">
        <div>未完成（人）</div>
        <div>{{ statistics.uncompletedCount }}</div>
      </div>
      <div class="over-item">
        <div>无效报告（份）</div>
        <div>{{ statistics.invalidReport }}</div>
      </div>
  </div>
  <!-- 表格部分 -->
  <div class="table-box">
    <el-table
        :data="tableData"
        :border="false"
        style="width: 100%"
        height="350px"
        :header-cell-style="{ 'background-color': '#f5f7fa' }"
        :expand-row-keys="expandedRowKeys"
        row-key="id"
    >
      <!-- 表格下拉部分 -->
      <el-table-column type="expand">
        <template #default="props">
          <div class="scale-box" v-for="item in props.row.family">
            <div class="left">
              <div style="padding: 10px 10px">{{ item.name }}</div>
              <div style="padding-left: 10px">
                <el-progress :percentage="item.complishedStatus" />
              </div>
            </div>
            <div class="right">
              <el-button type="primary" :disabled="item.complishedStatus !== 100">测评报告</el-button>
              <el-button type="primary" :disabled="item.complishedStatus !== 100">答题记录</el-button>
              <el-button type="primary" @click="handleRedo(props.row, item)">重做</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="name" />
      <el-table-column label="账号" prop="account" />
      <el-table-column label="组织结构" prop="struct" min-width="200" />
      <el-table-column label="完成度" >
        <template #default="scope">
          {{ scope.row.complishedStatus }}%
        </template>
      </el-table-column>
      <el-table-column label="加入计划时间" >
        <template #default="scope">
          <span :style="{ 'color': scope.row.isJoinPlanTime ? '' : 'red' }">{{ scope.row.isJoinPlanTime ? '已加入' : '未加入' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100" >
        <template #default="scope">
          <el-button type="primary" size="small" @click="toggleExpand(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="struct">河南工业和信息化职业学院</div>
</template>

<style scoped>
.search-box {
    padding: 0px 0px 10px 10px;
}
.over-box {
  display: flex;
}
.over-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-left: 10px;
  width: 18%;
  height: 80px;
  font-weight: 700;
  color: #188dff;
  background-color: #e8f4ff;
}
.table-box {
  margin-top: 10px;
  padding-left: 10px;
}
.scale-box {
  display: flex;
}
.scale-box .left {
  width: 30%;
  height: 70px;
  background-color: #f9f9f9;
}
.scale-box .right {
  display: flex;
  align-items: center;
  overflow: hidden;
  width: 21%;
  height: 70px;
  background-color: #f9f9f9;
}
.struct {
  text-align: center;
  padding: 10px 0;
  color: rgba(0, 0, 0, 0.4);
}
</style>
